<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加职务' : '编辑职务'"
    width="500px"
    align-center
    :close-on-click-modal="false"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="职务名称" prop="positionName">
        <ElInput
          v-model="formData.positionName"
          placeholder="请输入职务名称"
          maxlength="20"
          show-word-limit
        />
      </ElFormItem>

      <ElFormItem label="职级" prop="positionLevel">
        <ElInput
          v-model="formData.positionLevel"
          placeholder="请输入职级"
          maxlength="50"
        />
      </ElFormItem>

      <ElFormItem label="排序" prop="positionSort">
        <ElInputNumber
          v-model="formData.positionSort"
          :min="0"
          :max="10000"
          :step="1"
          placeholder="请输入排序值"
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem label="备注" prop="positionRemark">
        <ElInput
          v-model="formData.positionRemark"
          type="textarea"
          :rows="4"
          placeholder="请输入备注信息"
          maxlength="300"
          show-word-limit
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit" v-ripple>
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import {
    apiPositionSaveDataUsingPost,
    apiPositionUpdateDataUsingPost,
    type ApiPositionVo
  } from '@/api'

  interface Props {
    visible: boolean
    type: 'add' | 'edit'
    positionData?: ApiPositionVo
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false)

  // 表单数据
  const formData = reactive({
    id: undefined as number | undefined,
    positionName: '',
    positionLevel: '',
    positionSort: 0,
    positionRemark: ''
  })

  // 表单验证规则
  const rules: FormRules = {
    positionName: [
      { required: true, message: '请输入职务名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    positionSort: [
      { required: true, message: '请输入排序值', trigger: 'blur' },
      { type: 'number', min: 0, max: 10000, message: '排序值范围 0-10000', trigger: 'blur' }
    ]
  }

  // 初始化表单数据
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.positionData
    const row = props.positionData

    if (isEdit && row) {
      Object.assign(formData, {
        id: row.id,
        positionName: row.positionName || '',
        positionLevel: row.positionLevel || '',
        positionSort: row.positionSort || 0,
        positionRemark: row.positionRemark || ''
      })
    } else {
      Object.assign(formData, {
        id: undefined,
        positionName: '',
        positionLevel: '',
        positionSort: 0,
        positionRemark: ''
      })
    }
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.positionData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      let res
      if (dialogType.value === 'add') {
        // 添加职务
        res = await apiPositionSaveDataUsingPost({
          body: {
            positionName: formData.positionName,
            positionLevel: formData.positionLevel,
            positionSort: formData.positionSort,
            positionRemark: formData.positionRemark
          }
        })
      } else {
        // 编辑职务
        res = await apiPositionUpdateDataUsingPost({
          body: {
            id: formData.id,
            positionName: formData.positionName,
            positionLevel: formData.positionLevel,
            positionSort: formData.positionSort,
            positionRemark: formData.positionRemark
          }
        })
      }

      if (res) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
        dialogVisible.value = false
        emit('submit')
      } else {
        ElMessage.error('操作失败')
      }
    } catch (error: any) {
      if (error !== false) {
        // false 是表单验证失败返回的
        console.error('提交职务数据失败:', error)
        ElMessage.error('操作失败')
      }
    } finally {
      submitLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
</style>
